<template>
  <el-drawer :title="title" :visible.sync="visible" :direction="direction" :size="drawerSize"
    :before-close="handleClose" custom-class="drawer-container">
    <div class="drawer-content">
      <div class="drawer-body">
        <el-form ref="elForm" :model="form" :rules="rules" size="medium" label-width="100px">
          <el-row :gutter="24">
            <el-col :span="24">
              <el-form-item label="标题" prop="name">
                <el-input v-model="form.name" placeholder="请输入名称" maxlength="50" clearable show-word-limit />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="24">
              <el-form-item label="备注" prop="description">
                <el-input v-model="form.description" type="textarea" placeholder="请输入备注"
                  :autosize="{ minRows: 4, maxRows: 4 }" maxlength="200" clearable show-word-limit></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="内容" prop="content">
            <vue-ueditor-wrap v-model="form.content" :config="myConfig"></vue-ueditor-wrap>
          </el-form-item>
        </el-form>
      </div>
      <div class="drawer-footer">
        <el-button type="primary" @click="submitForm">提交</el-button>
        <el-button @click="resetForm">取消</el-button>
      </div>
    </div>
  </el-drawer>
</template>

<script>
import { addArticle, getArticle, updateArticle } from "@/api/zx/article";
import VueUeditorWrap from 'vue-ueditor-wrap';

export default {
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: ''
    },
    articleId: {
      type: [String, Number],
      default: null
    }
  },
  components: {
    VueUeditorWrap
  },
  data() {
    return {
      myConfig: {
        autoHeightEnabled: false,
        initialFrameHeight: 540,
        initialFrameWidth: '100%',
        enableAutoSave: true,
        serverUrl: process.env.VUE_APP_BASE_API + '/api/ueditor/controller?userId=' + this.$store.getters.userInfo.userId,
        UEDITOR_HOME_URL: '/ueditor/',
        zIndex: 1,
        wordCount: true,
        maximumWords: 5000,
        toolbarTopOffset: 0,
        scaleEnabled: false
      },
      form: {
        id: undefined,
        name: undefined,
        content: undefined,
        description: undefined,
        status: "1"
      },
      rules: {
        name: [
          { required: true, message: "标题不能为空", trigger: "blur" }
        ],
        content: [
          { required: true, message: "内容不能为空", trigger: "blur" }
        ]
      },
      // 抽屉方向
      direction: 'rtl',
      // 抽屉宽度
      drawerSize: 'calc(100vw - 200px)',
    }
  },
  watch: {
    articleId: {
      handler(val) {
        if (val) {
          // 强制刷新数据
          this.form = {
            id: undefined,
            name: undefined,
            content: undefined,
            description: undefined,
            status: "1"
          };
          getArticle(val).then(response => {
            this.form = response.data;
          });
        } else {
          this.resetForm();
        }
      },
      immediate: true
    },
    visible(val) {
      if (val) {
        // 在nextTick中执行，确保DOM已更新
        this.$nextTick(() => {
          const drawerBody = document.querySelector('.el-drawer__body');
          if (drawerBody) {
            drawerBody.scrollTop = 0;
          }
        });
      }
    }
  },
  methods: {
    submitForm() {
      this.$refs['elForm'].validate(valid => {
        if (!valid) return;

        // 检查富文本内容长度
        const content = this.form.content || '';
        // 创建一个临时的div来获取纯文本内容
        const div = document.createElement('div');
        div.innerHTML = content;
        const contentLength = div.textContent.trim().length;
        
        if (contentLength > 5000) {
          this.$message({
            message: '富文本内容超出最大长度限制（5000个字符）',
            type: 'warning'
          });
          return;
        }
        
        if (this.form.id != undefined) {
          updateArticle(this.form).then(response => {
            if (response.code === 200) {
              this.msgSuccess("修改成功");
              this.$emit('success');
              this.$emit('close');
             
            }
          });
        } else {
          addArticle(this.form).then(response => {
            if (response.code === 200) {
              this.msgSuccess("新增成功");
              this.$emit('success');
              this.$emit('close');
             
            }
          });
        }
      })
    },
    resetForm() {
      // 重置表单数据
      this.form = {
        id: undefined,
        name: undefined,
        content: undefined,
        description: undefined,
        status: "1"
      };
      
      // 重置表单验证
      if (this.$refs['elForm']) {
        this.$refs['elForm'].clearValidate();
      }
      //关闭
      this.$emit('close');
    },
    handleClose() {
      this.resetForm();
      this.$emit('close');
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-drawer__header{
  font-size: 16px;
  font-weight: 500;
  color: #000000;
  margin-bottom: 0;
  padding: 16px 20px;
  border-bottom: 1px solid #e8e8e8;
}

.drawer-container {
  .drawer-content {
    height: 100%;
    display: flex;
    flex-direction: column;

    .drawer-body {
      flex: 1;
      overflow-y: auto;
      padding: 20px;
    }

    .drawer-footer {
      height: 60px;
      padding: 10px 20px;
      border-top: 1px solid #e8e8e8;
      display: flex;
      justify-content: flex-end;
      align-items: center;
      background-color: #fff;

      .el-button {
        margin-left: 10px;
      }
    }
  }
}

// 防止富文本编辑器工具栏浮动
::v-deep .edui-editor {
  .edui-editor-toolbarbox {
    position: relative !important;
    top: auto !important;
    z-index: auto !important;
  }
  
  .edui-editor-iframeholder {
    position: relative !important;
  }
}
</style>
